//
// Created by 77873 on 2020/10/12 0012.
//

#include "DataQueue.h"

DataQueue::DataQueue(PlayStatus *ps) {
    this->playStatus=ps;
    pthread_mutex_init(&pthreadMutex, NULL);
    pthread_cond_init(&pthreadCond, NULL);
}


DataQueue::~DataQueue() {
    clearAvpacket();

    pthread_mutex_destroy(&pthreadMutex);
    pthread_cond_destroy(&pthreadCond);
}

int DataQueue::pushAvpacket(AVPacket *pkt) {
    pthread_mutex_lock(&pthreadMutex);
    queuePacket.push(pkt);

    pthread_cond_signal(&pthreadCond);
    pthread_mutex_unlock(&pthreadMutex);
    return 0;
}

int DataQueue::popAvpacket(AVPacket *pkt) {

    pthread_mutex_lock(&pthreadMutex);
    while (playStatus != NULL && !playStatus->isExit) {
        if (queuePacket.size() > 0) {
            AVPacket *avPacket = queuePacket.front();
            /**
             * 拷贝操作 （将pkt的值拷贝到 avpacket中）
             */
            if (av_packet_ref(pkt, avPacket) == 0) {
                queuePacket.pop();
            }
            av_packet_free(&avPacket);
            av_free(avPacket);
            avPacket = NULL;
            break;
        } else {
            pthread_cond_wait(&pthreadCond, &pthreadMutex);
        }
    }
    pthread_mutex_unlock(&pthreadMutex);
    return 0;
}

int DataQueue::getQueueSIze() {
    int size = 0;
    pthread_mutex_lock(&pthreadMutex);
    size = queuePacket.size();
    pthread_mutex_unlock(&pthreadMutex);
    return size;
}

void DataQueue::clearAvpacket() {

    pthread_cond_signal(&pthreadCond);
//    LOGE("clearAvpaket pthread_mutex_lock");
    pthread_mutex_lock(&pthreadMutex);

    while (!queuePacket.empty()) {
        AVPacket *avPacket = queuePacket.front();
        queuePacket.pop();

        av_packet_free(&avPacket);
        av_free(avPacket);
        avPacket = NULL;
    }
    pthread_mutex_unlock(&pthreadMutex);
//    LOGE("clearAvpaket pthread_mutex_unlock");
}

void DataQueue::noticeQueue() {
    pthread_cond_signal(&pthreadCond);
}

